const fse = require('fs-extra')
const ejs = require('ejs')
const { glob } = require('glob')
let inquirer; 
/**
 * targetPath: '/Users/zhangjie/Desktop/xqc-ink-install',
 * soucePath: '/Users/zhangjie/.xqc-ink-cli/template/node_modules/.store/xqc-ink-cli-template-custom-vue2@1.0.5/node_modules/xqc-ink-cli-template-custom-vue2/template'
 */
module.exports = async function (options){
    const { targetPath, soucePath, templateInfo, projectInfo} = options
    inquirer = (await import('inquirer')).default
    const promptAnswer = await inquirer.prompt([{
        type: 'input',
        name: 'description',
        message: '请输入项目描述信息',
        default: '', 
        validate: function(v){
            const done = this.async();
            setTimeout(function() {
                if (!v) {
                    done('请输入项目描述');
                    return;
                }
                done(null, true);
            }, 0);
        }
    }])
    projectInfo.description = promptAnswer.description
    try {
        // fse.ensureDirSync(templatePath)
        // fse.ensureDirSync(targetPath)
        fse.copySync(soucePath, targetPath) 
        // egj render 忽略
        const temlateIgnore = templateInfo.ignore || []
        const ignore = ['**/node_modules/**', 'public/**', ...temlateIgnore];
        await ejsRender({ ignore : ignore, targetPath, projectInfo: projectInfo }) 
    }
    catch (error) {
        throw error
    }
    finally {
        // cliSpinner.stop(true)
        // log.sucess('模板安装成功')
        console.log('模板安装成功')
    }
} 

/**
 * 通过glob找到package.json
 * @param {*} ignore 
 * @returns 
 */
async function ejsRender(option){
    const dir = option.targetPath;
    const projectInfo = option.projectInfo
    return new Promise(async (resolve, reject) => {
        await glob('**', {
            cwd: dir,
            ignore: option.ignore || '',
            nodir: true
        })
        .catch(err => reject(err))
        .then(files => {
            Promise.all(files.map(file => {
                const filePath = path.join(dir, file)
                return new Promise( (resolve1, reject1) => {
                    // ejs 仅仅是拿到渲染之后的结果 并没有修改源文件并写入
                    ejs.renderFile(filePath, projectInfo, {},(err, result) => {
                        if(err){
                            reject1(err)
                        }
                        else {
                            fse.writeFileSync(filePath, result)
                            resolve1(result)
                        }
                    })
                })
            }))
            .then(e => {  
                resolve('1')
            })
            .catch(err => reject(err))
        })
    })
}